/**
 * 深拷贝
 * @param {Object | Array} obj
 * @returns {Object | Array}
 */
const $deepcopy = (obj) => {
  if (!(typeof obj === 'object')) {
    return;
  }
  for (var key in obj) {
    if (
      obj.hasOwnProperty(key) &&
      (obj[key] == null || obj[key] === undefined || obj[key] === '')
    ) {
      delete obj[key];
    }
  }
  // return obj;
  return JSON.parse(JSON.stringify(obj));
};

/**
 * 手机号码脱敏
 * @param value 手机号码
 * @returns {void|never|string} 4-7位*号替换手机号
 */
const $hidePhone = (value) => {
  if (value) {
    return value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }
};
/**
 * 创建文件blob地址
 * @param {Blob} file
 * @returns {String}
 */
const $createObjectURL = (file) => {
  return window.URL.createObjectURL(file);
};
/**
 * 回收blob地址
 * @param {String} url
 */
const $revokeObjectURL = (url) => {
  window.URL.revokeObjectURL(url);
};
/**
 * 下载Excel文件
 * @param {} data
 * @param {} data
 * 直接下载文件
 */
const $downloadExcel = (data, filename, deco = true) => {
  if ('msSaveOrOpenBlob' in navigator) {
    // Microsoft Edge and Microsoft Internet Explorer 10-11
    window.navigator.msSaveOrOpenBlob(data, filename);
  } else {
    // standard code for Google Chrome, Mozilla Firefox etc
    const url = $createObjectURL(data);
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = deco ? decodeURI(filename) : filename;
    document.body.appendChild(anchor);
    anchor.click();
    $revokeObjectURL(url);
  }
};

/**
 * yyyy-MM-dd计算除年龄
 * @param {String} obj
 * @returns {String}
 */
const $age = (obj) => {
  let r = obj.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
  if (r == null) return false;
  let d = new Date(r[1], r[3] - 1, r[4]);
  if (
    d.getFullYear() == r[1] &&
    d.getMonth() + 1 == r[3] &&
    d.getDate() == r[4]
  ) {
    //eslint-disable-line
    let Y = new Date().getFullYear();
    return Y - r[1];
  }
};

// 日期转换
const $formatDate = (date, format) => {
  date = new Date(date);
  if (!format) {
    format = 'yyyy-MM-dd hh:mm:ss';
  }

  var map = {
    M: date.getMonth() + 1, // 月份
    d: date.getDate(), // 日
    h: date.getHours(), // 小时
    m: date.getMinutes(), // 分
    s: date.getSeconds(), // 秒
    q: Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
    var v = map[t];
    if (v !== undefined) {
      if (all.length > 1) {
        v = '0' + v;
        v = v.substr(v.length - 2);
      }
      return v;
    } else if (t === 'y') {
      return (date.getFullYear() + '').substr(4 - all.length);
    }
    return all;
  });
  return format;
};
// 分转换为元
const $moneyCompany = (e) => {
  return (parseFloat(e) / 100).toFixed(2);
};
const $filterSex = (val) => {
  return { 0: '男', 1: '女', 2: '' }[val];
};
// 映射枚举
const $filterEnums = (val, data, type) => {
  let obj = {};
  data.map((item) => {
    if (type) {
      obj[item.real_value] = item.label || item.name;
    } else {
      obj[item.value || item.id] = item.label || item.name;
    }
  });
  // console.log(obj[val], val, data, type)
  return obj[val];
};
// 映射枚举
const $filterEnumsArr = (val, data, id = 'id', name = 'name') => {
  let arr = [];
  data.map((item) => {
    val.split(',').forEach((valid) => {
      if (item[id] == valid) {
        arr.push(item[name]);
      }
    });
  });
  return arr;
};
// 根据省市区code获取省市区名称
const $filterRegion = (obj, data) => {
  let provinces = data.filter((item) => {
    return item.value === obj.province;
  });
  let citys =
    provinces[0] &&
    provinces[0].children &&
    provinces[0].children.length &&
    provinces[0].children.filter((item) => {
      return item.value === obj.city;
    });
  let areas =
    citys[0] &&
    citys[0].children &&
    citys[0].children.length &&
    citys[0].children.filter((item) => {
      return item.value === obj.area;
    });
  return [provinces[0].label, citys[0].label, areas[0].label];
};

// 树结构通过子节点id查找对应的节点名称
const $filterTree = (id, data) => {
  if (data && data.length) {
    var temp = [];
    var forFn = function(arr, id) {
      for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (item.value === id) {
          temp.push(item.label);
          break;
        } else {
          if (item.children) {
            forFn(item.children, id);
          }
        }
      }
    };
    forFn(data, id);
    return temp[0];
  }
};

// 树结构通过子节点的id查找到父节点
const $familyTree = (id, data) => {
  console.log(11, id, data);
  if (data && data.length) {
    let temp = [];
    let bchearr = [];
    let forFn = function(arr, id) {
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i];
        if (item.value === id) {
          temp.push(item.value);
          if (item.parent) {
            forFn(data, item.parent);
          }
          break;
        } else {
          if (item.children) {
            forFn(item.children, id);
          }
        }
      }
    };
    forFn(data, id);
    for (var i = 0; i <= temp.length; i++) {
      bchearr.push(temp.pop());
    }
    temp[0] && bchearr.push(temp[0]);
    return bchearr;
  }
};
// 统一处理frequency
const $filterFrequency = (data) => {
  if (data && data.length) {
    let timeArr = [],
      cache = {},
      indices = [],
      result = [],
      week = [],
      period = '';
    data.forEach((ele) => {
      let date = ele.day_of_Week === 7 ? '日' : $convertNum(ele.day_of_Week);
      timeArr.push({
        time:
          ele.start_time.substring(0, 5) + '~' + ele.end_time.substring(0, 5),
        date: date,
      });
    });
    timeArr.forEach((item, i) => {
      let time = item.time;
      let index = cache[time];
      if (index !== undefined) {
        indices[index].push(i);
      } else {
        cache[time] = indices.length;
        indices.push([i]);
      }
    });
    indices.forEach((item) => {
      item.forEach((index) => {
        result.push(timeArr[index]); // 依次把index对应的元素data[index]添加进去即可
      });
    });
    indices.forEach((item, index) => {
      let date = '';
      item.forEach((ele, $index) => {
        date =
          $index !== 0
            ? date + '、' + result[ele].date
            : date + result[ele].date;
      });
      week.push(date + ' ' + result[item[0]].time);
    });
    week.forEach((ele, index) => {
      period = index !== 0 ? period + '  周' + ele : period + ele;
    });
    return period;
  }
};
const $convertNum = (val) => {
  let tmpnewchar = '';
  switch (val) {
    case 1:
      tmpnewchar = '一';
      break;
    case 2:
      tmpnewchar = '二';
      break;
    case 3:
      tmpnewchar = '三';
      break;
    case 4:
      tmpnewchar = '四';
      break;
    case 5:
      tmpnewchar = '五';
      break;
    case 6:
      tmpnewchar = '六';
      break;
    case 7:
      tmpnewchar = '七';
      break;
    case 8:
      tmpnewchar = '八';
      break;
    case 9:
      tmpnewchar = '九';
      break;
    case 10:
      tmpnewchar = '十';
      break;
    case 11:
      tmpnewchar = '十一';
      break;
  }
  return tmpnewchar;
};
export default {
  $deepcopy,
  $hidePhone,
  $revokeObjectURL,
  $createObjectURL,
  $downloadExcel,
  $age,
  $formatDate,
  $moneyCompany,
  $filterSex,
  $filterEnums,
  $filterRegion,
  $familyTree,
  $filterTree,
  $filterFrequency,
  $convertNum,
  $filterEnumsArr,
};
